package org.llc.oauthclient.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.llc.common.model.Result;
import org.llc.oauthclient.service.CodeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 授权码Controller
 *
 * @author llc
 * @date 2020/1/8 10:11
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/resource/client")
public class CodeController {

    /**
     * 授权码获取Token Service
     */
    private final CodeService codeService;

    public CodeController(CodeService codeService) {
        this.codeService = codeService;
    }

    /**
     * 测试
     * 根据redirect_uri拿到code
     * <p>隐藏模式下返回token到返回code的控制器上，但是获取不到</p>
     * <p>
     * 令牌的位置是 URL 锚点（fragment），而不是查询字符串（querystring），
     * 这是因为 OAuth 2.0 允许跳转网址是 HTTP 协议，因此存在"中间人攻击"的风险，
     * 而浏览器跳转时，锚点不会发到服务器，就减少了泄漏令牌的风险。
     * </p>
     *
     * @param code 一次性获取token码
     * @return java.lang.String
     * @author llc
     * @date 2020/1/15 10:16
     */
    @GetMapping("/authorize/code")
    public Result save(@RequestParam(value = "code", required = false) String code,
                       @RequestParam(value = "state", required = false) String state,
                       @RequestParam(value = "error", required = false) String error,
                       @RequestParam(value = "error_description", required = false) String errorDescription) {
        if (StringUtils.isBlank(error) && StringUtils.isBlank(errorDescription)) {
            log.info("code -> {} state -> {} ", code, state);
            // 远程服务调用得时候是http请求这里用微服务调用代替
            return codeService.getTokenByClientAuthorizationCode(code);
        }
        return Result.failed(error,errorDescription);
    }
}

